Classes & Exceptions

Classes

Classes are central elements in Object-oriented programming (OOP)

A class structure defines an object, its properties, and all the operations one can apply to it. Moreover, it allows the creation of multiple instances of the same object, each with its own properties, and to apply the same operations to all of them. Another key concept is the one of inheritance, defining a new class from an existing one by simply inheriting all its properties and operations.

In Python, a class contains attributes (variables) and methods (functions). Syntactically, it is defined similarly to a function, replacing the def keyword with class and requiring a colon : at the end of the first line. The name of a class should be CamelCase1 (or CapWords).

  • 1 CamelCase (🇫🇷: casse de chameau): the name comes from the “bumpy” look of its letters as in the Wikipedia illustration below

  • For instance, in sklearn, the Logistic Regression class is named LogisticRegression, and can be loaded and investigated as follows:

    from sklearn.linear_model import LogisticRegression
    dir(LogisticRegression)
    ['__annotations__',
     '__class__',
     '__delattr__',
     '__dict__',
     '__dir__',
     '__doc__',
     '__eq__',
     '__format__',
     '__ge__',
     '__getattribute__',
     '__getstate__',
     '__gt__',
     '__hash__',
     '__init__',
     '__init_subclass__',
     '__le__',
     '__lt__',
     '__module__',
     '__ne__',
     '__new__',
     '__reduce__',
     '__reduce_ex__',
     '__repr__',
     '__setattr__',
     '__setstate__',
     '__sizeof__',
     '__str__',
     '__subclasshook__',
     '__weakref__',
     '_check_feature_names',
     '_check_n_features',
     '_estimator_type',
     '_get_param_names',
     '_get_tags',
     '_more_tags',
     '_parameter_constraints',
     '_predict_proba_lr',
     '_repr_html_',
     '_repr_html_inner',
     '_repr_mimebundle_',
     '_validate_data',
     '_validate_params',
     'decision_function',
     'densify',
     'fit',
     'get_params',
     'predict',
     'predict_log_proba',
     'predict_proba',
     'score',
     'set_params',
     'sparsify']

    Usually, a class contains some class methods that can be seen as functions inside the class.

    • The first argument of a (non-static) method is usually called self: it is a mandatory element. This self argument is for self-reference. Self is a convention and not a Python keyword, so any other name can be used instead of self (e.g., this or me or in_place_of_self).

    • Some method names have a specific meaning, for instance:

      • __init__: name of the method invoked when creating the object (instantiation)
      • __call__: method invoked when calling the object
      • __str__: method invoked when a class has a representation as a string, e.g., when passing it to the print function
      • see Python documentation for more special names.

    Example

    Let us define a simple Point class, representing a point in the plane (i.e., a point in \mathbb{R}^2):

    class Point(object):
        """A class to represent planar points."""
    
        def __init__(self, x, y):
            """Create a new point (x, y)."""
            self.x = x
            self.y = y
    
        def translate(self, dx, dy):
            """Translate the point by dx and dy."""
            self.x += dx
            self.y += dy
    
        def __str__(self):
            return f"Point: [{self.x:.3f}, {self.y:.3f}]"
    Note

    If you are not familiar with printing in Python, start with the new f-strings format; see for instance: https://zetcode.com/python/fstring/.

    To create a new instance of the class Point you run the following code:

    p1 = Point(x=0, y=0)  # call __init__ ;

    Now, you can access the attributes of the object p1:

    print(p1.x)
    print(p1.y)
    print("{0}".format(p1))  # call __str__
    p1
    0
    0
    Point: [0.000, 0.000]
    <__main__.Point at 0x7f965d6636a0>

    To apply our translate method to the point p1:

    p1.translate(dx=1, dy=1)
    print(p1.translate)
    print(p1)
    print(type(p1))
    <bound method Point.translate of <__main__.Point object at 0x7f965d6636a0>>
    Point: [1.000, 1.000]
    <class '__main__.Point'>

    Implicitly, the previous command is equivalent to Point.translate(p1, dx=1, dy=1). Indeed, you can check the output of the following command:

    p1 = Point(x=0, y=0)
    Point.translate(p1, dx=1, dy=1)
    print(p1)
    Point: [1.000, 1.000]
    Note

    You might have already used that syntax with the “dot” notation in numpy, for instance when executing numpy functions as follows

    import numpy as np
    rng = np.random.default_rng(seed=12345)
    a = rng.random((3, 3))
    a.mean(axis=0)
    array([0.50063315, 0.29820069, 0.60097848])

    In that case, a was an instance of the numpy.ndarray class (see numpy documentation for details on this class):

    type(a)
    numpy.ndarray

    Built-in method: __call__

    MyClass(arg1, arg2, ...) is a shorthand for MyClass.__call__(arg1, arg2, ...), so this allows writing classes where the instances behave like functions and can be called like a function

    class Sum:
        def __init__(self):
            print("Instance Created")
    
        # Defining __call__ method
        def __call__(self, a, b):
            print(a + b)
    
    # Instance created
    sum_as_a_function = Sum()
    
    # __call__ method will be called
    sum_as_a_function(10, 20)
    Instance Created
    30

    A test function of interest is isinstance which allows checking if an object is of the correct class. For instance, one can check if sum_as_a_function is an instance of Sum:

    isinstance(sum_as_a_function, Sum)
    True

    similarly one can test if it is an instance of Point:

    isinstance(sum_as_a_function, Point)
    False

    Another example of a callable is given below with a simple Counter class:

    class Counter:
        def __init__(self):
            self.count = 0
    
        def increment(self):
            self.count += 1
    
        def __call__(self):
            self.increment()

    Then, performing the following commands you can check how the __call__ method is called:

    counter = Counter()
    print(counter.count)
    counter.increment()
    print(counter.count)
    counter()
    print(counter.count)
    0
    1
    2

    In particular, note that a method of a class can modify the state of a particular instance. This does not alter the other instantiations of the class.

    To go further

    This example and more details on callable are described in detail in this Real Python post.

    EXERCISE: Gaussian class

    Implement a class Gaussian with attributes mean and std with a method

    • __str__ returning a string with the expression of the density
    • __eq__ testing the equality of two instances. You should use numpy.isclose()
    • __add__ implementing the addition of independent Gaussian, or more precisely their pdfs (probability density functions)
    • __radd__ implementing the addition of independent Gaussian, or more precisely their pdfs (probability density functions)

    Note: when executing a+b what really happens is that the add method of the a: object is called a.__add__(b).

    g1 = Gaussian(0.0, 1.0)
    g2 = Gaussian(1.0, 2.0)
    g3 = Gaussian(2.0, 2.0)
    g4 = Gaussian(3.0, 3.0)
    
    print(g1)
    print(g2)
    print(g3)
    print(g4)
    print(g2 + g1)
    print(sum([g1, g2, g3]))
    print(sum([g1, g2, g3]) == g4)
    pdf: exp(-(x - 0.000)^2 / (1.000*2^2)) / sqrt(2 * pi * 1.000^2)
    pdf: exp(-(x - 1.000)^2 / (2.000*2^2)) / sqrt(2 * pi * 2.000^2)
    pdf: exp(-(x - 2.000)^2 / (2.000*2^2)) / sqrt(2 * pi * 2.000^2)
    pdf: exp(-(x - 3.000)^2 / (3.000*2^2)) / sqrt(2 * pi * 3.000^2)
    pdf: exp(-(x - 1.000)^2 / (2.236*2^2)) / sqrt(2 * pi * 2.236^2)
    pdf: exp(-(x - 3.000)^2 / (3.000*2^2)) / sqrt(2 * pi * 3.000^2)
    True

    Inheritance

    Classes can inherit methods from other classes. You can use super (Latin word for “above”) to access the parent class from a child class. This is useful when you want to extend the functionality of the inherited method.

    A simple test consists of checking whether a class has inherited from another one. issubclass allows one to check this heritage property. For instance, we can check that the following IsoGaussian is a subclass of the Gaussian class we have created above:

    class IsoGaussian(Gaussian):
        def __init__(self, mean):
            super().__init__(mean, 1.0)
    
    gg1 = IsoGaussian(3)
    print(gg1)
    issubclass(IsoGaussian, Gaussian)
    pdf: exp(-(x - 3.000)^2 / (1.000*2^2)) / sqrt(2 * pi * 1.000^2)
    True
    To go further

    For more information on super, see for instance this Real Python Tutorials.

    EXERCISE: inheritance

    What is the inheritance for the LogisticRegression class in scikit-learn? In particular, not that inheritance could be multiple, i.e.. a class can inherit from several classes.

    Hint: use the __bases__ attribute of the class.

    from sklearn.linear_model import LogisticRegression
    a=LogisticRegression()
    print(a.__class__.__bases__)
    (<class 'sklearn.linear_model._base.LinearClassifierMixin'>, <class 'sklearn.linear_model._base.SparseCoefMixin'>, <class 'sklearn.base.BaseEstimator'>)

    Many other examples can be found in the scikit-learn package (see for instance the module Linear Model often used in machine learning or statistics).

    Exceptions

    This section is inspired by Fabien Maussion’s lecture on Scientific Programming, and describes how to handle exceptions in python.

    • In python errors are handled through Exceptions
    • An error throws an Exception interrupting the normal code execution
    • Execution can overpass such an issue inside a bloc with try - except
    • A typical use case: stop the program when an error occurs:
    def my_function(arguments):
    
        if not verify(arguments):
            raise Exception("Invalid arguments")
    
        # ...
        # Keep working if the exception is not raised
    To go further

    The list of possible errors is available here: https://docs.python.org/3/library/exceptions.html#bltin-exceptions and includes NameError, ImportError, AssertionError etc.

    try - except - finally syntax

    One may use try, except or finally to prevent errors to stop the program:

    try:
        # Part 1: Normal code goes here
    except:
        # Part 2: Code for error handling goes here
        # This code is not executed unless Part 1
        # above generated an error
    finally:
        # Optional: This clause is executed no matter what,
        # and is generally used to release external resources.

    Let us consider the following example to understand the syntax better:

    try:
        print("test_var testing:")
        e = 4
        print(test_var) # raise an error: the test_var variable is not defined
    except NameError:
        print("Caught an exception: test_var does not exist")
    finally:
        print("This code is executed no matter what")
    
    print("The program keep continuing... it does not freeze!")
    print(f"Beware! the affectation step: e = {e} was executed.")
    test_var testing:
    Caught an exception: test_var does not exist
    This code is executed no matter what
    The program keep continuing... it does not freeze!
    Beware! the affectation step: e = 4 was executed.

    To obtain some information on the error: it is possible to access the instance of the Exception class thrown by the program through the following syntax:

    try:
        print("test")
        print(testtt)  # Error: the variable testtt is not defined
    except Exception as name_exception:
        print("Caught an exception:", name_exception)
    test
    Caught an exception: name 'testtt' is not defined

    A common use case is to test if the import of a package was successful or not. For instance, if you try loading a package pooooch that is not installed on your machine, the following code will raise an error:

    import pooooch
    ModuleNotFoundError: No module named 'pooooch'

    If you would like the program to continue even if the package is not installed, you can use the following syntax:

    try:
        import pooch
    except Exception as e:
        print(e)

    An exhaustive list of exceptions be found here: https://docs.python.org/3/library/exceptions.html.

    The with statement

    Important

    You have to run the following lines at a location where a directory called scripts/ containing a function hello-world.py exists. The one used in the lecture is available here if you have not cloned the course repository (if you have it is available in scripts/). You can of course create your own if you prefer.

    fname = "./scripts/hello-world.py"
    
    with open(fname) as file:  # Use file to refer to the file object
        data = file.read()
        print(data)
        # at the end of the code chunk, the file.__exit__() method is called (i.e., file.close() is done automatically)
    tatjpjepj.
    

    Now

    fname = "scripts/hello-world_do_not_exist.py"
    try:
        # 1/0  # Yncomment at some point and run
        file = open(fname)
        data = file.read()
        print(data)
    except FileNotFoundError:
        print("File not found!")
    except (RuntimeError, TypeError, NameError, ZeroDivisionError):
        print("Specific Error message 2")
    finally:
        file.close()  # Important line to release access to the file!
    File not found!
    EXERCISE: Improving the Gaussian class

    Create a sub-class GaussianBis where you check if the user has provided float arguments (see also assert and isinstance routines). Print a custom explicit error message if it is not the case.

    Scope

    e = 0
    print(e)
    
    for i in range(1):
        e = 1
    
    print(e)
    
    
    def f():
        e = 2
    
    print(e)

    Conclusion: e is only “visible” inside the function definition. See https://realpython.com/python-scope-legb-rule/ for more information on this topic.

    Manipulate file names across platforms

    Each OS (Linux / Windows /Mac) might have a different syntax to describe a file path. The following would avoid naming conflict due to each OS syntax and could be important for your project if you work with colleagues with a different OS from yours.

    import os
    
    print(os.path.join('~', 'work', 'src'))
    print(os.path.join(os.getcwd(), 'new_directory'))
    os.path.expanduser?
    print(os.path.expanduser(os.path.join('~', 'work', 'src')))
    EXERCISE: Create a bunch of files

    Write a simple script that creates, in the sub-directory scripts, the following text files: myDb_000.txt, myDb_001.txt, myDb_002.txt, …, myDb_049.txt. The i-th file should contain a single line with the average of the i first digits of pi.

    Hint:

    • You might need zero padding.
    • You can check what the following code does.
    file = open("copy.txt")
    file.write("Your text goes here")
    file.close()
    • You might also need some precision for the digits of \pi, hence using mpmath instead of numpy.
    from mpmath import mp
    import numpy as np
    
    if not os.path.isdir("script"):
        os.mkdir("script")
    
    for i in range(2, 50):
    
    
    for i in range(2, n_tot + 2):
        val = '0' + str(i)
        print(str(f"{i:{val}}"))

    References

    Back to top